<template>
  <div class="page-container">
    <el-card shadow="hover" class="content-card">
      <template #header>
        <h3 class="card-title">请假申请</h3>
      </template>
      
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        size="large"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="请假类型" prop="leaveTypeId">
              <el-select v-model="formData.leaveTypeId" placeholder="请选择请假类型" style="width: 100%">
                <el-option
                  v-for="type in leaveTypes"
                  :key="type.id"
                  :label="type.typeName"
                  :value="type.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假时长" prop="duration">
              <el-input-number
                v-model="formData.duration"
                :min="0.5"
                :max="365"
                :step="0.5"
                :precision="1"
                placeholder="请输入请假天数"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="formData.startTime"
                type="datetime"
                placeholder="选择开始时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                @change="calculateDuration"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="formData.endTime"
                type="datetime"
                placeholder="选择结束时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                @change="calculateDuration"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="请假事由" prop="reason">
          <el-input
            v-model="formData.reason"
            type="textarea"
            :rows="6"
            placeholder="请详细描述请假事由"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="large" @click="handleSubmit" :loading="loading">
            提交申请
          </el-button>
          <el-button size="large" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getLeaveTypes, submitApplication } from '@/api/leave'
import { useRouter } from 'vue-router'

const router = useRouter()
const formRef = ref(null)
const loading = ref(false)
const leaveTypes = ref([])

const formData = reactive({
  leaveTypeId: null,
  startTime: '',
  endTime: '',
  duration: 1,
  reason: ''
})

const rules = {
  leaveTypeId: [
    { required: true, message: '请选择请假类型', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请输入请假时长', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请输入请假事由', trigger: 'blur' },
    { min: 10, message: '请假事由至少10个字符', trigger: 'blur' }
  ]
}

// 加载请假类型
const loadLeaveTypes = async () => {
  try {
    const res = await getLeaveTypes()
    leaveTypes.value = res.data || []
  } catch (error) {
    console.error('加载请假类型失败:', error)
  }
}

// 计算请假时长
const calculateDuration = () => {
  if (formData.startTime && formData.endTime) {
    const start = new Date(formData.startTime)
    const end = new Date(formData.endTime)
    const diff = end - start
    if (diff > 0) {
      formData.duration = Math.ceil(diff / (1000 * 60 * 60 * 24) * 10) / 10
    }
  }
}

// 提交申请
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      // 转换日期格式为时间戳
      const submitData = {
        leaveTypeId: formData.leaveTypeId,
        startTime: new Date(formData.startTime).getTime(),
        endTime: new Date(formData.endTime).getTime(),
        duration: formData.duration,
        reason: formData.reason
      }
      
      await submitApplication(submitData)
      ElMessage.success('请假申请提交成功')
      handleReset()
      // 跳转到我的请假页面
      router.push('/leave/my-list')
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      loading.value = false
    }
  })
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
}

onMounted(() => {
  loadLeaveTypes()
})
</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}

.content-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.content-card :deep(.el-card__body) {
  flex: 1;
  padding: 30px;
  overflow-y: auto;
}

.card-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
